package com.kun.order.service.mq;

import com.alibaba.fastjson.JSON;
import com.kun.api.IOrderService;
import com.kun.common.constant.ShopCode;
import com.kun.pojo.domain.TradeOrder;
import com.kun.pojo.domain.TradePay;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.pay.topic}", consumerGroup = "${mq.pay.consumer.group.name}", messageModel = MessageModel.BROADCASTING)
public class PaymentListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IOrderService orderService;

    @Override
    public void onMessage(MessageExt message) {
        log.info("接收到支付信息");
        try {
            // 1. 解析消息内容
            TradePay tradePay = JSON.parseObject(new String(message.getBody(), StandardCharsets.UTF_8), TradePay.class);
            // 2. 更改订单支付状态为已支付
            orderService.lambdaUpdate().set(TradeOrder::getPayStatus, ShopCode.SHOP_ORDER_PAY_STATUS_IS_PAY.getCode())
                    .eq(TradeOrder::getOrderId, tradePay.getOrderId()).update();
            log.info("更改订单支付信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("更改订单支付信息失败");
        }
    }
}
